package com.itheima.service.impl;

import com.itheima.doman.Result;
import com.itheima.exception.DeptDeleteException;
import com.itheima.mapper.DeptMapper;
import com.itheima.doman.pojo.Dept;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static com.itheima.constant.MessageConstant.DELETE_DEPT_HAVE_EMP_FAIL;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    /**
     *  查询所有部门
     * @return
     */
    @Override
    public List<Dept> findAll() {
        return deptMapper.selectAll();
    }

    /**
     *  删除部门
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
//        - 删除部门时：如果部门下有员工，则不允许删除该部门，并给前端提示错误信息：对不起，当前部门下有员工，不能直接删除！
        if (deptMapper.countEmpByDeptId(id) > 0){
            throw new DeptDeleteException(DELETE_DEPT_HAVE_EMP_FAIL);
        }else {
            deptMapper.deleteById(id);
        }
    }

    /**
     *  添加部门
     * @param dept
     */
    @Override
    public void addDept(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insertDept(dept);
    }

    /**
     *  根据id查询部门
     * @param id
     * @return
     */
    @Override
    public Dept findById(Integer id) {
        return deptMapper.selectById(id);
    }

    /**
     *  修改部门
     * @param dept
     */
    @Override
    public void updateDept(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateDept(dept);
    }
}
